//var arr = getvl1('ids');
var arr = sessionStorage.getItem('ids');
///getAllGold();
//列表
searchMyaddress();

function searchMyaddress() {
	$("#shouhuodizList").html("");
	$.ajax({
		url: urlcore + "/api/address/selectAddressAll2",
		type: "get",
		dataType: 'json',
		contentType: "application/json;charset=utf-8",
		success: function(data) {
			if(data.success == true) {
				$.each(data.data, function(i, n) {
					var levelName = '';
					if(n.level == 1) {
						levelName = '默认地址';
					}
					var thislist =
						'<li class="levelName1">' +
						'<h5>' + n.province + '' + n.city + '(' + n.userName + '&nbsp;收)<em>' + levelName + '</em></h5>' +
						'<p hidden="hidden" class="levelName2"><input type="text" class="levelName"value="' + levelName + '"/><input type="text" class="addressId" value="' + n.id + '"/></p>' +
						'<p>' + n.userPhone + '</p>' +
						'<p>' + n.province + '' + n.city + '' + n.county + '' + n.address + '</p>' +
						'<a href="24.0.0wode_dizhi.html?id=' + n.id + '" class="dingdan_dizhi_xiugai">修改</a>' +
						'<span class="xuanzhong">' +
						'<img src="images/dizhi_xuanzhong.png" />' +
						'</span>' +
						'</li>';
					$('#shouhuodizList').append(thislist);

					//地址选择
					$('.dingdan_dizhi li').on('click', function() {
						$(this).addClass('Show1').siblings().removeClass('Show1');
					});

				});
				//向后台传递地址id
				$(function() {
					$('.levelName1').click(function() {
						var addressId = $(this).find('p[class*=levelName2]').find('input[class*=addressId]').val();
						/*$.ajax({
							url: urlcore + "/api/expressPrice/getAddressId?addressId=" + addressId,
							type: "get",
							dataType: 'json',
							contentType: "application/json;charset=utf-8",
							success: function(data) {
								if(data.success == true) {

								}
							}
						})*/
						//选择地址并刷新页面运费
						loadMyEssayFromDindan(arr,addressId);
						//location.reload();
					})
					var addressId = '';
					$('.levelName1').find('p[class*=levelName2]').each(function(i, val1) {
						if($(val1).find('input[class*=levelName]').val() == '默认地址') {
							addressId = $(val1).find('input[class*=addressId]').val();
						}
					})
					loadMyEssayFromDindan(arr,addressId);
					/*if(addressId != '') {
						$.ajax({
							url: urlcore + "/api/expressPrice/getAddressId?addressId=" + addressId,
							type: "get",
							dataType: 'json',
							contentType: "application/json;charset=utf-8",
							success: function(data) {
								if(data.success == true) {

								}
							}
						})
					}*/
				});

			} else if(data.code == 'OVERTIME') {
				var thisUrl = window.location.href;
				//alert(thisUrl);
				if(thisUrl.indexOf('1.0.0denglu.html') <= -1) {
					top.window.location.href = "1.0.0denglu.html";
				}

			} else {
				if(data.msg != '空数据') {
					layer.alert(data.msg)
				} else {
					$('#thiscount').text(0);
				}
			}

		},
		error: function() {
			layer.alert("error");
		}
	});
}

/*if(arr != '') {
	//确认订单信息列表
	loadMyEssayFromDindan(arr,);
}
*/
function loadMyEssayFromDindan(arr,addressId) {

	$("#goodsByDindan").html("");
	$.ajax({
		url: urlcore + "/api/goodsCar/selectGoodsCarList2?ids=" + arr,
		type: "get",
		dataType: 'json',
		async: 'false',
		contentType: "application/json;charset=utf-8",
		success: function(data) {
			if(data.success == true) {
				var deductibleGoldNum = 0; //抵扣金币
				var deductibleMoney = 0; //抵扣金额
				var moneyByShops = 0;
				var orderMoney = 0;
				
				$.each(data.data, function(i, n) {
					var saleNums = 0; //所有商品个数
					var moneyByShop = 0;
					var weight=0;//单种商品总重量
					//商品
					var goodsList = '';
					$.each(n.goodsList, function(i, m) {
						
						
						//单价商品购买个数
						var saleNum = 0;
						var goodsStockList = ''; //库存
						$.each(m.myStockList, function(i, y) {
							saleNum += y.saleNum;
							goodsStockList +=
								'<tr>' +
								'<td>' +
								'<span>' + y.size.sizeName + '</span>' +
								'</td>' +
								'<td>' + y.colour.colourName + '</td>' +
								'<td>' + y.saleNum + '件</td>' +
								'<td class="saleNum" hidden="hidden"><input type="hidden" class="saleNum1" value="' + y.saleNum + '"/></td>' +
								'</tr>';

						});
						//优惠价
						var packRate = 0;
						var goodsType = 0;
						if(m.goodsCar != null) {
							weight+=m.weight*m.goodsCar.goodsNumber;//单种商品总重量
							
							if(m.goodsCar.goodsType == 1) {
								/*if(saleNum >= m.packNumber) {
									packRate = m.goodsCar.packRate;
								} else {
									packRate = m.tradePrice;
								}*/
								packRate = m.goodsCar.packRate;
								goodsType = 1;
							} else {
								packRate = m.goodsCar.packRate;
								goodsType = m.goodsCar.goodsType;
							}
						} else {
							packRate = m.tradePrice;
							goodsType = 4;
						}
						/*	if(m.goldRate != 0) {
								//计算金币
								var goldMoney = packRate * saleNum * (m.goldRate / 100);
								var goldNum = Math.round(goldMoney * 40);
								if(goldNum <= 1) {
									goldMoney = 0;
									goldNum = 0;
								}
								var allGold = sessionStorage.getItem("allGold");
								if(allGold >= goldNum) {
									sessionStorage.setItem("allGold", allGold - goldNum);
									deductibleGoldNum += goldNum;
									deductibleMoney += goldMoney;
								}
							}*/

						saleNums += saleNum;

						//单件商品金额
						var money = packRate * saleNum;
						//购买单个店铺商品总金额
						moneyByShop += money;
						//moneyByShop=moneyByShop;

						goodsList +=
							'<div class="clearfix dingdan_goods">' +
							'<dl class="fl clearfix goodsId1">' +
							'<dt>' +
							'<a href="2.2.0goods_detail.html?id=' + m.id + '"><img src="' + isHasImg(m.coverUrl) + '" /></a>' +
							'</dt>' +
							'<dd class="goodsId2">' +
							'<a href="2.2.0goods_detail.html?id=' + m.id + '"><h5>' + m.goodsTitle + '</h5></a>' +
							'<h6>&yen;' + packRate + '</h6>' +
							'<input type="hidden" class="goodsId" value="' + m.id + '"/>' +
							'<input type="hidden" class="price" value="' + packRate + '"/>' +
							/*	'<input type="hidden" class="goldMoney" value="' + goldMoney + '"/>' +
								'<input type="hidden" class="goldNum" value="' + goldNum + '"/>' +*/
							'<input type="hidden" class="goodsType" value="' + goodsType + '"/>' +
							'</dd>' +
							'</dl>' +
							'<div class="fl detail_goods_table">' +
							'<table>' +
							goodsStockList +
							'</table>' +
							'</div>' +
							'<div class="fr detail_goods_price">' + fmoney(money, 2) + '</div>' +
							'</div>';

					});
					
					var freightMoney=0;
					if(addressId != '') {
						$.ajax({
							url: urlcore + "/api/expressPrice/selectShopExpressPriceByAddressId?addressId=" + addressId+"&shopId="+n.id+"&weight="+weight,
							type: "get",
							dataType: 'json',
							async: false,
							contentType: "application/json;charset=utf-8",
							success: function(data) {
								if(data.success == true) {
                                   freightMoney=data.data;
								}
							}
						})
					}

					
					if(moneyByShop <= n.freightMoney) {
						moneyByShop = 0;
					}
					var myPayMoney = moneyByShop + freightMoney;
					//累加金额
					moneyByShops += myPayMoney;
					//orderMoney += moneyByShop;
					
					var selectFreightMoney ='';
					if(freightMoney != null && freightMoney > 0) {

						selectFreightMoney = '<select id="giveType" value="2" class="giveType" oninput="changeGiveType(this);" name="giveType">' +
							'<option value="2">快递</option>' +
							'<option value="3">货运到付</option>' +
							'</select>';
					} else {
						selectFreightMoney = '<select id="giveType" value="1" class="giveType" oninput="changeGiveType(this);" name="giveType">' +
							'<option value="1">包邮</option>' +
							'</select>';
					}
					//var myPayMoney = moneyByShops - n.freightMoney;
					var thislist =
						'<div class="huo_dingdan">' +
						'<div class="putong_list_title">' +
						'<a href="10.1.0dianpu_detail.html?id=' + n.id + '"><em>' + n.storeName + '</em></a>' +
						'<input type="hidden" class="shopId" value="' + n.id + '"/>' +
						'</div>' +
						'<div class="detail_goods">' +
						goodsList +
						'<div class="clearfix remark1">' +
						'<div class="dingdan_liuyan clearfix remark2">' +
						'<label>留言备注：</label>' +
						'<textarea class="remark" id="remark" name="remark" placeholder="请输入留言备注"></textarea>' +
						'</div>' +
						'<div class="dingdan_peisong giveType1">' +
						'<div class="fl giveType2">' +
						'<label>配送方式：</label>' +
						selectFreightMoney +
						'</div>' +
						'<span class="fr myFreightMoney" >' + freightMoney + '</span>' +
						'</div>' +
						'</div>' +
						'<div class="dingdan_heji">店铺合计(含运费)：<input type="hidden" class="freightMoney"  value="' + freightMoney + '"/><input type="hidden" class="orderMoney"  value="' + moneyByShop + '"/><input type="hidden" class="moneyByShop"  value="' + myPayMoney + '"/><span class="myPayMoney">' + fmoney(myPayMoney, 2) + '</span></div>' +
						'</div>' +
						'</div>';

					$('#goodsByDindan').append(thislist);
				});

				/*	var dm = toDecimal(deductibleMoney);
				var goldNumAndMoney = '您的商品可用金币' + Math.round(deductibleGoldNum) + '抵消金额' + dm + '元';
				$('.goldNumAndMoney').html(goldNumAndMoney);
				if(dm <0 || Math.round(deductibleGoldNum) < 0) {
					$('.goldNumAndMoney').hide();
					$('.goldNumMessage').show();
				}
*/
				/*	$("input[name='inlineCheckbox3']").click(function() {
					
					var mm=$(this).parent('div[class*=x1]').nextAll('div[class*=a4]').find('span[class*=payallmoney]').text();
					//支付总金额
					if($(this).is(':checked')) {
						var allGold = sessionStorage.getItem("allGold");

						if(allGold < deductibleGoldNum) {
							//alert("账户金币不够用了！");
							$('.allGlodNum').html('账户金币不够用了！');
							return;
						}

						$("#payallmoney1").text(fmoney((mm - deductibleMoney), 2));
						$("#payallmoney").text(mm - deductibleMoney);
					} else {
						var mmm=parseFloat(mm)+parseFloat(deductibleMoney);
						$("#payallmoney1").text(fmoney(mmm, 2));
						$("#payallmoney").text(mmm);
					}
				})
*/
				$("#payallmoney1").text(fmoney(moneyByShops, 2));
				$("#payallmoney").text(moneyByShops);

			} else if(data.code == 'OVERTIME') {
				var thisUrl = window.location.href;
				//alert(thisUrl);
				if(thisUrl.indexOf('1.0.0denglu.html') <= -1) {
					top.window.location.href = "1.0.0denglu.html";
				}

			} else {
				if(data.msg != '空数据') {
					layer.alert(data.msg)
				} else {
					$('#thiscount').text(0);
				}
			}

		},
		error: function() {
			layer.alert("error");
		}
	});

}

//修改快递
function changeGiveType(giveType) {

	var orderMoney = $(giveType).parents('.remark1').next('.dingdan_heji').find('input[class*=orderMoney]').val(); //订单金额
	var moneyByShop = $(giveType).parents('.remark1').next('.dingdan_heji').find('input[class*=moneyByShop]').val(); //支付金额
	var myFreightMoney = $(giveType).parents('.remark1').next('.dingdan_heji').find('input[class*=freightMoney]').val(); //运费
	var payallmoney = $(giveType).parents('#goodsByDindan').parent().parent().parent().find('div[class*=a4]').find('span[class*=payallmoney]').text(); //支付总额
	if(giveType.value == 2) {

		$(giveType).parents('.giveType1').find('.myFreightMoney').show();
		var moneyByShop1 = parseFloat(orderMoney) + parseFloat(myFreightMoney);
		$(giveType).parents('.remark1').next('.dingdan_heji').find('span[class*=myPayMoney]').text(fmoney(moneyByShop1, 2)); //显示
		$(giveType).parents('.remark1').next('.dingdan_heji').find('input[class*=moneyByShop]').val(moneyByShop1); //隐藏

		var money = parseFloat(payallmoney) + parseFloat(myFreightMoney);
		$("#payallmoney1").text(fmoney(money, 2)); //支付总额
		$("#payallmoney").text(money); //支付总额隐藏

	} else {
		$(giveType).parents('.giveType1').find('.myFreightMoney').hide();

		var moneyByShop1 = parseFloat(moneyByShop) - parseFloat(myFreightMoney);
		$(giveType).parents('.remark1').next('.dingdan_heji').find('span[class*=myPayMoney]').text(fmoney(orderMoney, 2));
		$(giveType).parents('.remark1').next('.dingdan_heji').find('input[class*=moneyByShop]').val(orderMoney);

		var money = parseFloat(payallmoney) - parseFloat(myFreightMoney);
		$("#payallmoney1").text(fmoney(money, 2));
		$("#payallmoney").text(money);
	}
}

$(function() {

	$(".topay").click(function() {
		var myPay = $(this).prev('span[class*=payallmoney]').text();
		//把支付金额存入
		sessionStorage.setItem('money', myPay);

		var addressId = 0;
		var show1 = $('input[class*=shopId]').parent().parent().parent().prev().prev().prev().find('li[class*=Show1]');
		if(show1.length > 0) {
			addressId = $(show1).find('p[class*=levelName2]').find('input[class*=addressId]').val();
		} else {
			$('input[class*=shopId]').parent().parent().parent().prev().prev().prev().find('li[class*=levelName1]').find('p[class*=levelName2]').each(function(i, val1) {
				if($(val1).find('input[class*=levelName]').val() == '默认地址') {
					addressId = $(val1).find('input[class*=addressId]').val();
				}
			})
		}

		if(addressId == 0) {
			layer.alert("请选择收货地址");
			return;
		}
		var arrays = '[';
		var money = 0;
		var goldMoney1 = 0;
		var goldNum1 = 0;
		$('input[class*=shopId]').each(function(i, val) {
			//找到商品id
			//  var goodsId = $(this).parent().next().children('.dingdan_goods').find('dl[class*=goodsId1]').find('dd[class*=goodsId2]').find('input[class*=goodsId]').val();				

			//	goodsIds+=goodsId+",";
			var goodsIds = '';
			$(this).closest(".huo_dingdan").find('input[class*=goodsId]').each(function(i, g) {
				goodsIds += g.value + ",";
			}); //获取本店铺的所有商品

			//找到商品price
			//var price = $(this).parent().next().children().find('dl[class*=goodsId1]').find('dd[class*=goodsId2]').find('input[class*=price]').val();									

			//var goldMoney = $(this).parent().next().children().find('dl[class*=goodsId1]').find('dd[class*=goodsId2]').find('input[class*=goldMoney]').val();
			//goldMoney1 += goldMoney;
			//var goldNum = $(this).parent().next().children().find('dl[class*=goodsId1]').find('dd[class*=goodsId2]').find('input[class*=goldNum]').val();
			//goldNum1 = +goldNum;

			var goodsType = $(this).parent().next().children().find('dl[class*=goodsId1]').find('dd[class*=goodsId2]').find('input[class*=goodsType]').val();

			//留言
			var remark = $(this).parent().next().find('div[class*=remark1]').find('div[class*=remark2]').find('textarea[class*=remark]').val();
			//配送
			var giveType = $(this).parent().next().find('div[class*=remark1]').find('div[class*=giveType1]').find('div[class*=giveType2]').find('select[class*=giveType]').val();
			//订单金额
			var orderMoney = $(this).parent().next().find('div[class*=dingdan_heji]').find('input[class*=orderMoney]').val();
			//支付金额
			var moneyByShop = $(this).parent().next().find('div[class*=dingdan_heji]').find('input[class*=moneyByShop]').val();
			//money += moneyByShop;

			//运费
			var freightMoney = $(this).parent().next().find('div[class*=dingdan_heji]').find('input[class*=freightMoney]').val();
			var t = $(this).parent().next().find('div[class*=dingdan_goods]').find('div[class*=detail_goods_table]').children().children().find('td[class*=saleNum]').find('input[class*=saleNum1]');
			var n = 0; //购买件数
			if(t.length > 0) {
				$.each(t, function(i, v) {
					n += parseInt(v.value);
				});
			}
			var goodsId = goodsIds.substring(0, goodsIds.length - 1);
			if(freightMoney == "") {
				freightMoney = "0.0";
			}

			/*if(document.getElementById("inlineCheckbox3").checked) {
				//把支付金额存入
				//sessionStorage.setItem('money', (money - goldMoney1));
				if(i == 0) {
					arrays += '{"shopId":' + val.value + ',"goodsId":"' + goodsId + '","goldMoney":"' + 0.00 + '","goldNum":' + 0 + ',"addressId":' + addressId + ',"goodsNumber":' + n + ',"orderMoney":' + moneyByShop + ',"payMoney":' + moneyByShop + ',"freightMoney":' + freightMoney + ',"giveType":' + giveType + ',"remark":"' + remark + '","saveMoney":"' + 0 + '","userCouponId":"' + 0 + '","orderType":' + goodsType + '}';
				} else {
					arrays += ',{"shopId":' + val.value + ',"goodsId":"' + goodsId + '","goldMoney":"' + 0.00 + '","goldNum":' + 0 + ',"addressId":' + addressId + ',"goodsNumber":' + n + ',"orderMoney":' + moneyByShop + ',"payMoney":' + moneyByShop + ',"freightMoney":' + freightMoney + ',"giveType":' + giveType + ',"remark":"' + remark + '","saveMoney":"' + 0 + '","userCouponId":"' + 0 + '","orderType":' + goodsType + '}';
				}

			} else {*/
			//sessionStorage.setItem('money', money);
			if(i == 0) {
				arrays += '{"shopId":' + val.value + ',"goodsId":"' + goodsId + '","goldMoney":' + 0.00 + ',"goldNum":' + 0 + ',"addressId":' + addressId + ',"goodsNumber":' + n + ',"orderMoney":' +toDecimal(orderMoney)+ ',"payMoney":' + toDecimal(moneyByShop) + ',"freightMoney":' + toDecimal(freightMoney) + ',"giveType":' + giveType + ',"remark":"' + remark + '","saveMoney":"' + 0 + '","userCouponId":"' + 0 + '","orderType":' + goodsType + '}';
			} else {
				arrays += ',{"shopId":' + val.value + ',"goodsId":"' + goodsId + '","goldMoney":' + 0.00 + ',"goldNum":' + 0 + ',"addressId":' + addressId + ',"goodsNumber":' + n + ',"orderMoney":' + toDecimal(orderMoney) + ',"payMoney":' + toDecimal(moneyByShop) + ',"freightMoney":' + toDecimal(freightMoney) + ',"giveType":' + giveType + ',"remark":"' + remark + '","saveMoney":"' + 0 + '","userCouponId":"' + 0 + '","orderType":' + goodsType + '}';
			}
			//}

		});

		arrays += ']';
		if(arrays === undefined || arrays.length == 0) {
			return;
		}
		$.ajax({
			url: urlcore + '/api/order/addValet2',
			type: "post",
			contentType: "application/json;charset=utf-8",
			data: JSON.stringify({
				"myOrder": arrays
			}),
			dataType: "json",
			success: function(data) {
				if(data.success == true) {

					var orderId = new Array();
					$.each(data.data, function(i, n) {
						orderId.push(n.id);
					})
					sessionStorage.setItem("orderId", orderId);
					window.location.href = "choice_pay.html";
					// sessionStorage.setItem('moneyByShop');
				} else if(data.code == 'OVERTIME') {
					var thisUrl = window.location.href;
					if(thisUrl.indexOf('login.html') <= -1) {
						top.window.location.href = "login.html";
					}
				} else {
					alert(data.msg);
				}
			},
			error: function() {
				layer.alert("error");
			}
		});

	})
})

function getAllGold() {
	$.ajax({
		url: urlcore + "/api/userAccount/selectAccount",
		type: "get",
		dataType: 'json',
		contentType: "application/json;charset=utf-8",
		success: function(data) {
			if(data.success == true) {
				var da = data.data;
				var allGold = 0;
				if(da != null) {
					if(da.allGold != null) {
						allGold = da.allGold
					}
				}

				var glodNum = '您的账户剩余金币总数为:' + allGold;
				sessionStorage.setItem("allGold", allGold);
				//allGold=da.allGold;
				$('.allGlodNum').html(glodNum);
			} else if(data.code == 'OVERTIME') {
				var thisUrl = window.location.href;
				if(thisUrl.indexOf('login.html') <= -1) {
					top.window.location.href = "login.html";
				}
			} else {
				alert(data.msg);
			}
		},
		error: function() {
			alert("error");
		}
	});
}

//保留两位小数 
//功能：将浮点数四舍五入，取小数点后2位 
function toDecimal(x) {
	var f = parseFloat(x);
	if(isNaN(f)) {
		return;
	}
	f = Math.round(x * 100) / 100;
	return f;
}
//保留两位小数 
function returnFloat(value) {
	var value = Math.round(parseFloat(value) * 100) / 100;
	var xsd = value.toString().split(".");
	if(xsd.length == 1) {
		value = value.toString() + ".00";
		return value;
	}
	if(xsd.length > 1) {
		if(xsd[1].length < 2) {
			value = value.toString() + "0";
		}
		return value;
	}
}